package com.powernode.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.BusinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName AuthenticationFailureHandlerImpl
 * @Description 登录失败处理器
 * @Date 2024/07/20 20:12
 */
@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType(HttpConstants.APPLICATION_JSON);
        request.setCharacterEncoding(HttpConstants.UTF_8);
        // 创建统一响应对象
        Result<Object> result = new Result<>();
        result.setCode(BusinessEnum.OPERATION_FAIL.getCode());
        if (exception instanceof BadCredentialsException){
            result.setMsg("用户名或密码错误");
        } else if (exception instanceof UsernameNotFoundException){
            result.setMsg("用户不存在");
        } else if (exception instanceof AccountExpiredException) {
            result.setMsg("账号已过期");
        } else if (exception instanceof AccountStatusException) {
            result.setMsg("账号已锁定");
        } else if (exception instanceof InternalAuthenticationServiceException) {
            result.setMsg(exception.getMessage());
        } else {
            result.setMsg(BusinessEnum.OPERATION_FAIL.getDesc());
        }
        String resultStr = new ObjectMapper().writeValueAsString(result);
        PrintWriter writer = response.getWriter();
        writer.write(resultStr);
        writer.flush();
        writer.close();
    }
}
